from fastapi import Request, status
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException
from app.schemas.response import error_response, ResponseCode

async def http_exception_handler(request: Request, exc: StarletteHTTPException):
    """
    HTTP异常处理器
    """
    return JSONResponse(
        status_code=200,  # 始终返回200，错误信息在content中
        content=error_response(
            code=exc.status_code,
            msg=str(exc.detail)
        )
    )

async def validation_exception_handler(request: Request, exc: RequestValidationError):
    """
    请求参数验证异常处理器
    """
    error_details = exc.errors()
    error_messages = []
    
    for error in error_details:
        loc = " -> ".join([str(x) for x in error["loc"]])
        msg = f"{loc}: {error['msg']}"
        error_messages.append(msg)
    
    error_msg = "; ".join(error_messages)
    
    return JSONResponse(
        status_code=200,  # 始终返回200，错误信息在content中
        content=error_response(
            code=ResponseCode.BAD_REQUEST,
            msg=f"参数验证错误: {error_msg}"
        )
    )

async def general_exception_handler(request: Request, exc: Exception):
    """
    通用异常处理器
    """
    return JSONResponse(
        status_code=200,  # 始终返回200，错误信息在content中
        content=error_response(
            code=ResponseCode.INTERNAL_ERROR,
            msg=f"服务器内部错误: {str(exc)}"
        )
    ) 